package cn.leftsite.netty.test.websocket;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

import java.net.InetSocketAddress;

/**
 * 向ChatServer添加加密
 *
 * @author wangjinqiang
 * @date 2019-06-03
 */
public class SecurityChatServer extends ChatServer {
    private final SslContext context;

    public SecurityChatServer(SslContext context) {
        this.context = context;
    }

    @Override
    protected ChannelHandler createInitializer(ChannelGroup channelGroup) {
        // 返回之前创建的SecureChatServer-Initializer 以启用加密
        return new SecurityChatServerInitializer(channelGroup, context);
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        SelfSignedCertificate cert = new SelfSignedCertificate();
        SslContext context = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()).build();

        final SecurityChatServer endpoint = new SecurityChatServer(context);
        ChannelFuture future = endpoint.start(new InetSocketAddress(port));
        Runtime.getRuntime().addShutdownHook(new Thread(endpoint::destory));
        future.channel().closeFuture().syncUninterruptibly();
    }
}
